import React, { useEffect } from 'react';
import { Modal, Form, Input, Switch, InputNumber, Select, TimePicker } from 'antd';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = TimePicker;

const SettingForm = ({ visible, onCancel, onSubmit, initialValues, stores }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      if (initialValues) {
        let cleaningTime = [];
        if (initialValues.cleaning_time_slots) {
          try {
            const timeSlots = JSON.parse(initialValues.cleaning_time_slots);
            if (timeSlots && timeSlots.length > 0) {
              const firstSlot = timeSlots[0];
              cleaningTime = [moment(firstSlot.start, 'HH:mm'), moment(firstSlot.end, 'HH:mm')];
            }
          } catch (e) {
            console.error('Error parsing cleaning_time_slots:', e);
          }
        }
        form.setFieldsValue({
          ...initialValues,
          cleaning_time: cleaningTime,
        });
      } else {
        form.resetFields();
      }
    }
  }, [visible, initialValues, form]);

  const handleOk = () => {
    form.validateFields().then((values) => {
      const [startTime, endTime] = values.cleaning_time || [];
      const cleaningTimeSlots = (startTime && endTime)
        ? JSON.stringify([{ start: startTime.format('HH:mm'), end: endTime.format('HH:mm') }])
        : '[]';

      const submitData = {
        ...values,
        cleaning_time_slots: cleaningTimeSlots,
      };
      delete submitData.cleaning_time;
      onSubmit(submitData);
    });
  };

  return (
    <Modal
      title={initialValues ? '编辑保洁设置' : '新建保洁设置'}
      visible={visible}
      onCancel={onCancel}
      onOk={handleOk}
    >
      <Form form={form} layout="vertical">
        <Form.Item
          label="门店"
          name="store_id"
          rules={[{ required: true, message: '请选择门店' }]}
        >
          <Select placeholder="请选择门店" disabled={!!initialValues}>
            {stores.map((store) => (
              <Option key={store.id} value={store.id}>
                {store.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="启用保洁功能" name="enabled" valuePropName="checked">
          <Switch />
        </Form.Item>
        <Form.Item label="保洁时段" name="cleaning_time">
          <RangePicker format="HH:mm" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item label="预留保洁时间（分钟）" name="reserved_minutes">
          <InputNumber min={0} style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item label="自动分配任务" name="auto_assign" valuePropName="checked">
          <Switch />
        </Form.Item>
        <Form.Item label="提前通知时间（分钟）" name="notify_before_minutes">
          <InputNumber min={0} style={{ width: '100%' }} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default SettingForm;